package pers.acp.test.application.websocket

import io.gitee.zhangbinhub.acp.boot.websocket.AcpWebSocketServer
import io.gitee.zhangbinhub.acp.core.common.CommonTools.getDefaultCharset
import org.noear.solon.net.annotation.ServerEndpoint
import java.nio.ByteBuffer

@ServerEndpoint("/websocket/{userId}")
open class TestWebSocketServer : AcpWebSocketServer() {
    override var clientIdKey = "userId"
    override fun sessionOpen(handle: WebSocketServerHandle) {
        logAdapter.info("【websocket消息】【${handle.clientId}】有新的连接，连接id=${handle.clientId}")
        logAdapter.info("【websocket消息】连接参数：${handle.paramMap}")
        handle.sendMessage("CONNECT_SUCCESS")
    }

    override fun sessionClose(handle: WebSocketServerHandle?) {
        logAdapter.info("【websocket消息】【${handle?.clientIp}】【${handle?.clientId}】连接断开！")
    }

    override fun sessionError(handle: WebSocketServerHandle?, throwable: Throwable?) {
        logAdapter.error(if (throwable != null) throwable.message else "", throwable)
        logAdapter.error("【websocket消息】【${handle?.clientIp}】【${handle?.clientId}】用户错误,原因:" + (if (throwable != null) throwable.message else ""))
    }

    override fun receiveMessage(handle: WebSocketServerHandle, message: String?) {
        logAdapter.info("【websocket消息】【${handle.clientIp}】收到客户端【${handle.clientId}】发来的【文本】消息：$message")
        handle.sendMessage("我收到了：$message")
    }

    override fun receiveMessage(handle: WebSocketServerHandle, message: ByteBuffer?) {
        logAdapter.info("【websocket消息】【${handle.clientIp}】收到客户端【${handle.clientId}】发来的【二进制】消息：$message")
        handle.sendMessage(ByteBuffer.wrap("RECEIVE_BINARY_SUCCESS：".toByteArray(getDefaultCharset())))
    }
}